实用vue小技巧 | 您所在的位置:网站首页 › vue 默认显示子路由 › 实用vue小技巧 |
1.路由参数解耦
通常在组件中使用路由参数,大多数人会做以下事情。 export default { methods: { getParamsId() { return this.$route.params.id } } }在组件中使用 $route 会导致与其相应路由的高度耦合,通过将其限制为某些 URL 来限制组件的灵活性。正确的做法是通过 props 来解耦。 const router = new VueRouter({ routes: [{ path: /user/:id , component: User, props: true }] })将路由的 props 属性设置为 true 后,组件内部可以通过 props 接收 params 参数。 export default { props: [ id ], methods: { getParamsId() { return this.id } } }还可以通过 方法自定义属性 const router = new VueRouter({ routes: [{ path: /user/:id , component: User, props: (route) => ({ id: route.query.id }) }] }) 2.watch监听多个变量watch 本身不能监听多个变量。但是,我们可以通过返回具有计算属性的对象然后监听该对象来“监听多个变量”。 export default { data() { return { msg1: apple , msg2: banana } }, compouted: { msgObj() { const { msg1, msg2 } = this return { msg1, msg2 } } }, watch: { msgObj: { handler(newVal, oldVal) { if (newVal.msg1 != oldVal.msg1) { console.log( msg1 is change ) } if (newVal.msg2 != oldVal.msg2) { console.log( msg2 is change ) } }, deep: true } } } 3.程序化事件监听器当我们在页面挂载时定义一个定时器,往往需要在页面销毁时清除定时器。但仔细看的话this.timer 的唯一目的是能够在 beforeDestroy 中获取计时器编号,否则是无用的。 export default { mounted() { this.timer = setInterval(() => { console.log(Date.now()) }, 1000) }, beforeDestroy() { clearInterval(this.timer) } }可以发现上面代码分布在不同生命周期钩子函数中,这样代码分散不好管理,最理想情况应该是一个函数解决,同时逻辑也更集中更易读。我们可以通过使用 once 监听页面生命周期销毁来解决这个问题: export default { mounted() { this.creatInterval( hello ) this.creatInterval( world ) }, creatInterval(msg) { let timer = setInterval(() => { console.log(msg) }, 1000) this.$once( hook:beforeDestroy , function() { clearInterval(timer) }) } 4.监听组件生命周期通常我们使用 $emit 监听组件生命周期,父组件接收事件进行相关操作。 子组件 export default { mounted() { this.$emit( listenMounted ) } } 父组件vue的 @hook 可以用来监听子组件的生命周期,而不需要在组件内部做任何改动 |
CopyRight 2018-2019 实验室设备网 版权所有 |